package com.tn.controller.weigh;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.gitee.hifong45.FE;
import com.gitee.hifong45.Ret;
import com.tn.annotation.LogRequestInfo;
import com.tn.controller.alarm.common.model.CommonVO;
import com.tn.controller.alarm.common.model.PageInput;
import com.tn.controller.alarm.common.model.PageResult;
import com.tn.controller.alarm.common.model.weigh.mq.LicenseDto;
import com.tn.controller.alarm.common.model.weigh.vo.LiftingOrDropPoleRequest;
import com.tn.controller.alarm.common.model.weigh.vo.WeighLogInfoVO;
import com.tn.controller.alarm.common.model.weigh.vo.WeighLogQueryVO;
import com.tn.dao.mbpdao.Weightloginfo;
import com.tn.exception.DatabaseOperationFailedException;
import com.tn.exception.InvalidParamException;
import com.tn.service.weigh.IWeighService;
import com.tn.service.weigh.impl.WeighServiceImpl;
import com.tn.service.weigh.mq.LicenseMQ;
import com.tn.utils.CheckParamUtil;
import com.tn.utils.HTTPClientUtil;
import com.tn.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 磅房controller
 *
 * @program: tn_aucy_java
 * @author: yangjiayao
 * @create: 2021/11/16
 */
@Slf4j
@RestController
@RequestMapping("/aucy")
public class WeighController {
    /**
     * 磅房service
     */
    @Resource
    private IWeighService weighService;

    @Resource
    private WeighServiceImpl weighServiceImpl;


    /**
     * 注入
     *
     * @param weighService 磅房service
     */
    @Autowired
    public void setWeighService(IWeighService weighService) {
        this.weighService = weighService;
    }

    /**
     * 查询磅房当前信息
     *
     * @param queryVO 查询条件
     * @return 磅房当前信息
     * @throws InvalidParamException 异常
     */
    @RequestMapping("currentWeighInfo")
    public CommonVO<List<WeighLogInfoVO>> currentWeighInfo(@RequestBody PageInput<WeighLogQueryVO> queryVO)
            throws InvalidParamException {

        return weighService.currentWeighInfo();
    }




    @PostMapping("/stamp")
    public Ret<Object> stamp(@RequestBody Map<String,String>map) throws Exception {
        Map<String, Object> returnMap = weighService.stamp(map);
        return Ret.Ok(returnMap);
    }

//    /**
//     * 查询磅房日志信息
//     *
//     * @param queryVO 查询条件
//     * @return 磅房日志信息
//     * @throws InvalidParamException 异常
//     */
//    @RequestMapping("/weighLogInfo")
//    public CommonVO<PageResult<WeighLogInfoVO>> weighLogInfo(@RequestBody PageInput<WeighLogQueryVO> queryVO)
//            throws InvalidParamException {
//        CheckParamUtil.checkPageParam(queryVO.getCurPage(), queryVO.getPageSize());
//        CheckParamUtil.checkNullRequiredParam(queryVO.getData());
//        return weighService.getWeighLogInfo(queryVO.getCurPage(), queryVO.getPageSize(), queryVO.getData());
//    }

    /**
     * 查询磅房日志信息
     *
     * @param queryVO 查询条件
     * @return 磅房日志信息
     * @throws InvalidParamException 异常
     */
    @RequestMapping("/queryWeighLogInfo")
    public CommonVO<PageResult<WeighLogInfoVO>> queryWeighLogInfo(@RequestBody PageInput<WeighLogQueryVO> queryVO)
            throws InvalidParamException {
        CheckParamUtil.checkPageParam(queryVO.getCurPage(), queryVO.getPageSize());
        CheckParamUtil.checkNullRequiredParam(queryVO.getData());
        return weighService.queryWeighLogInfo(queryVO.getCurPage(), queryVO.getPageSize(), queryVO.getData());

    }
    /**
     * 导出磅房日志信息
     *
     * @return 磅房日志信息
     * @throws InvalidParamException 异常
     */
    @ResponseBody
    @PostMapping(value = "/weighLogInfoExport", produces = {"application/json;charset=UTF-8"})
    public void weighLogInfoExport(HttpServletRequest request, HttpServletResponse response,@RequestBody PageInput<WeighLogQueryVO> queryVO) throws IOException {
        weighService.exportWeighLogInfo(request,response,queryVO.getData());
    }

    @Autowired
    private LicenseMQ licenseMQ;

    @PostMapping("/start")
    public Ret<Object> start(@RequestBody Map<String,Object> paramMap) {
        licenseMQ.consumer("rpm/weight", JSON.toJSONString(paramMap));
        return Ret.Ok();
    }

    @PostMapping("/setweighloginfo")
    public Ret<Object> setWeighLogInfo(@RequestBody Weightloginfo info) {
        log.info("线上版执行开始，称重信息为{}" , JSON.toJSONString(info));
        weighServiceImpl.setWeightLogInfo(info);
        log.info("线上版执行结束");
        return Ret.Ok();
    }



    /**
     * 把货车和卡解绑
     * @param license
     * @return
     */
    @GetMapping("/updateTruckTagStatus")
    public Ret<Object> updateTruckTagStatus(String license) {
        log.info("updateTruckTagStatus入参："+JsonUtil.obj2String(license));
        FE.nullThrow(license, "license");
        Integer ret =weighServiceImpl.updateTruckTagStatus(license);
        return Ret.Ok(ret);
    }

    @PostMapping("/setWeighloginfoWithoutTask")
    public Ret<Object> setWeighloginfoWithoutTask(@RequestBody Weightloginfo info) throws Exception {
        log.info("离线版执行开始，称重信息为{}" , JSON.toJSONString(info));
        weighServiceImpl.setWeighloginfoWithoutTask(info);
        log.info("离线版执行结束");
        return Ret.Ok();
    }


    @PostMapping("/queryLastWeight")
    public Ret<Object> queryLastWeight(@RequestBody Weightloginfo info) throws Exception {
        float weight=weighServiceImpl.queryLastWeight(info);
        return Ret.Ok(weight);
    }

    /**
     * 根据毛重查询皮重，根据皮重查询毛重
     * @param info
     * @return
     * @throws Exception
     */
    @PostMapping("/selectWeightByOhtherWeight")
    public Ret<Object> selectWeightByOhtherWeight(@RequestBody Weightloginfo info) throws Exception {
        Float weight=weighServiceImpl.selectWeightByOhtherWeight(info);
        return Ret.Ok(weight);
    }

    @PostMapping("/addweighloginfo")
    public Ret<Object> addweighloginfo(@RequestBody Weightloginfo info) throws Exception {
        weighServiceImpl.addweighloginfo(info);
        return Ret.Ok();
    }


    @PostMapping("/editweighloginfo")
    public Ret<Object> editweighloginfo(@RequestBody Weightloginfo info) throws Exception {
        weighServiceImpl.editweighloginfo(info);
        return Ret.Ok();
    }


    @PostMapping("/isBindTag")
    public Ret<Object> isBindTag(@RequestBody Map<String,String> info) throws Exception {
        weighServiceImpl.isBindTag(info);
        return Ret.Ok();
    }


    /**
     * 修改车牌
     * @param licenseInfo 车牌信息
     * @return 修改车牌结果
     * @throws InvalidParamException 异常
     */
    @RequestMapping("/modifyLicense")
    public CommonVO<Object> modifyLicense(@RequestBody Map<String, String> licenseInfo)
            throws InvalidParamException, DatabaseOperationFailedException {
        CheckParamUtil.checkNullRequiredParam(licenseInfo.get("truckId"), licenseInfo.get("modifyLicense"));
        weighService.modifyLicense(licenseInfo.get("truckId"), licenseInfo.get("modifyLicense"));
        return new CommonVO<>();
    }
    /**
     * 修改称重结果
     * @param weighId 磅房ID
     * @param truckId 货车ID
     * @param roughWeight 毛重
     * @param tareWeight 皮重
     * @return
     */
    @PostMapping("/updateWeightInfo")
    public CommonVO<Object> updateWeight(Integer weighId, Integer truckId, String roughWeight, String tareWeight) {
        weighServiceImpl.updateWeight(weighId, truckId, roughWeight, tareWeight);
        return new CommonVO<>();
    }

    @GetMapping("/weighroom/in")
    public Ret<Object> truckInWeighRoom(String roomId, String roadId, Integer type, String licenseCamera, String licenseModify) {
        String str = StrUtil.format("货车进入磅房：({}){}-{} <-- {}({})", type, roomId, roadId, licenseCamera, licenseModify);
        log.info("磅房入闸记录: {}", str);
        return Ret.Ok();
    }


    @PostMapping("/selectLicenseMq")
    public Ret<Object> selectLicenseMq(@RequestBody LicenseDto info){
        return Ret.Ok( weighServiceImpl.selectLicenseMq(info));
    }

    @PostMapping("/deleteLicenseMq")
    public Ret<Object> deleteLicenseMq(@RequestBody LicenseDto info)  {
        log.info("删除车牌队列时间戳："+ JsonUtil.obj2String(info));
        weighServiceImpl.deleteLicenseMq(info);
        return Ret.Ok();
    }

    @PostMapping("/deleteAllLicenseMq")
    public Ret<Object> deleteAllLicenseMq(@RequestBody LicenseDto info)  {
        weighServiceImpl.deleteAllLicenseMq(info);
        return Ret.Ok( );
    }

    /**
     * 查询称重汇总的数据
     * @param queryVO
     * @return
     */
    @PostMapping("/queryWeightSum")
    public CommonVO<List<WeighLogInfoVO>> queryWeightSum(@RequestBody WeighLogQueryVO queryVO)  {
        return  weighServiceImpl.queryWeightSum(queryVO);
    }

    /**
     * 导出称重汇总的数据
     * @param queryVO
     * @return
     */
    @PostMapping(value = "/exportQueryWeightSum", produces = {"application/json;charset=UTF-8"})
    public void exportQueryWeightSum(HttpServletRequest request, HttpServletResponse response,@RequestBody WeighLogQueryVO queryVO)  throws IOException {
         weighServiceImpl.exportQueryWeightSum( request, response,queryVO);
    }


    /**
     * 导出称重汇总的数据Show
     * @param queryVO
     * @return
     */
    @PostMapping(value = "/exportQueryWeightSumShowDetail", produces = {"application/json;charset=UTF-8"})
    public CommonVO<PageResult<WeighLogInfoVO>> exportQueryWeightSumShowExcel(@RequestBody PageInput<WeighLogQueryVO> queryVO)  throws Exception {
        CheckParamUtil.checkPageParam(queryVO.getCurPage(), queryVO.getPageSize());
        CommonVO<PageResult<WeighLogInfoVO>> result = new CommonVO<>();
        result.setData(weighServiceImpl.onlineShowExcelPreview(queryVO));
        return result;
    }




    /**
     * 删除磅单
     * @return
     */
    @GetMapping("/deleteWeigh/{id}")
    public CommonVO<Object> deleteWeigh(@PathVariable("id")Long id)  {
        return  weighServiceImpl.deleteWeigh(id);
    }

//    /**
//     * 删除磅单
//     * @return
//     */
//    @GetMapping("/deleteWeigh/{id}")
//    public CommonVO<Object> deleteWeigh(@PathVariable("id")Long id ,@RequestHeader("username") String username)  {
//        log.info("删除榜单操作人为:{}" ,username);
//        return  weighServiceImpl.deleteWeigh(id);
//    }




    /**
     * 判断6号磅光栅是否被遮挡
     * @return
     */
    @GetMapping("/raster-shelter")
    public CommonVO<Object> rasterShelter() throws IOException, InterruptedException {
        return  weighServiceImpl.rasterShelter();
    }

    /**
     * netty调用
     * @return
     */
    @RequestMapping(value = "/accept-raster-signal", method = {RequestMethod.POST}, produces = "application/json")
    public CommonVO<Object> acceptRasterShelter(@RequestBody Map map){
        log.info("6号磅光栅返回值："+JsonUtil.obj2String(map));
        return  weighServiceImpl.acceptRasterShelter(map.get("data").toString());
    }


    /**
     * 抬杆落杆
     */
    @RequestMapping(value = "/liftingOrDropPole", method = {RequestMethod.POST}, produces = "application/json")
    public CommonVO<Object> LiftingOrDropPole(@RequestBody LiftingOrDropPoleRequest liftingOrDropPoleRequest) throws Exception {
        log.info("手动抬杆落杆结果："+JsonUtil.obj2String(liftingOrDropPoleRequest));
        String returnData="";
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(liftingOrDropPoleRequest.getUserName(), liftingOrDropPoleRequest.getPassWord());
        HTTPClientUtil.client.getState().setCredentials(AuthScope.ANY, creds);
        HTTPClientUtil.client.getHostConfiguration().setHost(liftingOrDropPoleRequest.getIp(), 80);
        String url = "/ISAPI/Security/userCheck";
        String  strOut= HTTPClientUtil.doGet(url);
        String url1="/ISAPI/Parking/channels/1/barrierGate";
        String inboundData="";
        if(liftingOrDropPoleRequest.getPoleOpertor()==0){
            inboundData="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                    "<BarrierGate version=\"2.0\" xmlns=\"http://www.isapi.org/ver20/XMLSchema\">\n" +
                    "<ctrlMode opt=\"open,close,lock,unlock\">open</ctrlMode>\n" +
                    "</BarrierGate>";
        }else {
            inboundData="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                    "<BarrierGate version=\"2.0\" xmlns=\"http://www.isapi.org/ver20/XMLSchema\">\n" +
                    "<ctrlMode opt=\"open,close,lock,unlock\">close</ctrlMode>\n" +
                    "</BarrierGate>";
        }
        returnData= HTTPClientUtil.doPut(url1, inboundData);
        log.info("手动抬杆落杆结果："+JsonUtil.obj2String(returnData));
        return new CommonVO<>(returnData);
    }

    /**
     * 查询车辆过磅信息，任务号，白名单等信息
     */
    @GetMapping("/query/{licence}")
    public Map query(@PathVariable("licence") String licence){
        return weighService.query(licence);
    }


}
